<template>
    <!-- #region register -->
    <div class="container">
        <div class="login">
            <div class="blurboard"></div>
            <div class="actualboard">
                <div class="picblock">
                    <div class="pic" @click="clickPic" @change='uploadPic' :style="cssPic">
                        <input type="file" ref="fileInput" id="fileInput" accept="image/*">
                    </div>
                </div>

                <div class="textblock">
                    <input type="text" class="textkuang" @keydown.enter="login" v-model="nameText">
                </div>
            </div>
        </div>
    </div>
    
    <!-- #endregion -->
</template>

<script setup name="login">
    import axios from 'axios'
    import settings  from "@/config/config"
    import { ref, onMounted, computed} from "vue"
    import router from '@/router'
    // #region 登陆界面
    const fileInput = ref()
    let picId = ref(-1)
    let nameText = ref()
    const cssPic = computed(() => {
        if (picId.value === -1) return {};
        const url = `${settings.backURL}/images?picId=${picId.value}`;
        return {
            'background-image': `url(${url})`,
        };
    });

    // 页面加载进入后查看是否存在登陆记录,若存在跳转
    onMounted(()=>{
        let userid = localStorage.getItem('userId')
        let picid = localStorage.getItem('picId')
        if (userid && picid) {
            router.push('/chessboard')
        }
    })
    
    
    function clickPic() {
        fileInput.value.click()
    }
    async function uploadPic() {
        const formdata = new FormData()
        formdata.append('file', fileInput.value.files[0])
        await axios.post(settings.backURL + "/api/uploadPic", formdata, {
            headers: {
                "Content-Type": "multipart/form-data",
            },
        }).then(function (response) {
            let jsonData = response.data
            picId.value = jsonData.picId
        }).catch((e)=>{
            console.log(e)
        })
    }
    // 登录
    async function login() {
        if (!nameText.value) {
            return
        }
        await axios.post(settings.backURL + '/api/login', {
            name: nameText.value,
            picid: picId.value
        }).then((response)=>{
            let userId = response.data.id
            let picId = response.data.picid
            // 存localstorage
            localStorage.setItem('userId', userId)
            localStorage.setItem('picId', picId)
            router.push('/chessboard')
        })
    }


    // #endregion
</script>

<style>
    @import "@/assets/css/login.css"
</style>